﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;
using AutoTAU.Properties;

namespace AutoTAU
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Set the process's priority to idle
            Process.GetCurrentProcess().PriorityClass =
                ProcessPriorityClass.BelowNormal;

            // Start the GUI notification manager
            GUINotificationManager.Start();

            // Check if username and password are present in the configuration
            if (Settings.Default.Username == "" || Settings.Default.Password == "")
            {
                // If not, show the settings dialog so that the user might enter proper credentials
                (new SettingsForm()).ShowDialog();
            }

            try
            {
                // Register Wifi notifications
                WifiAuthManager.Register();
            }
            catch (WifiRegisterException)
            {
                // AutoConfig error, display information dialog
                if (!Settings.Default.DontShowAutoConfigError)
                {
                    (new AutoConfigError()).ShowDialog();
                }
            }
            
            // Try to authenticate if Public-TAU is reachable
            Action authAction = WifiAuthManager.AuthenticateIfConnected;
            authAction.BeginInvoke(authAction.EndInvoke, null);

            // Make sure that the setting for autostart is reflected in the registry
            AutostartManager.Refresh();

            // Do we need to report this installation to the statistics server?
            if (Settings.Default.LastReportedInstallation !=
                Assembly.GetExecutingAssembly().GetName().Version.ToString())
            {
                // Start the statistics manager asynchronously
                Action statsAction = StatsManager.Start;
                statsAction.BeginInvoke(statsAction.EndInvoke, null);
            }

            Settings.Default.Save();

            Application.Run();
        }
    }
}